package com.besttone.search;

import com.besttone.search.R.color;
import com.besttone.search.model.PhoneInfo;
import com.besttone.search.util.PhoneUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private GridView grid;
	private DisplayMetrics localDisplayMetrics;
	private View view;
	private static final String city = "上海";
    private TextView view_provider;
    private TextView view_phoneNo;
	private EditText field_keyword;
	private Button btn_search;
	
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		view = this.getLayoutInflater().inflate(R.layout.main, null);
		setContentView(view);
		view_provider = (TextView) findViewById(R.id.provider);
		view_phoneNo = (TextView) findViewById(R.id.phoneNo);
		field_keyword = (EditText)findViewById(R.id.keyword);
		//field_keyword.setOnEditorActionListener(editorListener);
		btn_search = (Button) findViewById(R.id.search);
		btn_search.setOnClickListener(searchListner);
		//获取手机信息
		initPhoneInfo();
		localDisplayMetrics = getResources().getDisplayMetrics();
		 
		grid = (GridView)view.findViewById(R.id.my_grid);
		ListAdapter adapter = new GridAdapter(this);
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(mOnClickListener);
	}
	
    private Button.OnClickListener searchListner = new Button.OnClickListener() {
    	public void onClick(View v) {
				if(NetWorkStatus()) {
					String keyword = field_keyword.getText().toString();
					if(keyword!=null && !"".equals(keyword)) {
						Intent intent = new Intent();
						intent.setClass(MainActivity.this, ResultActivity.class);
						Bundle bundle = new Bundle();
			    		bundle.putString("city", city);
			    		bundle.putString("keyword", keyword);
			    		intent.putExtras(bundle);
			    		startActivity(intent);
					} else {
						Toast.makeText(MainActivity.this, "搜索关键词为空", Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(MainActivity.this, "网络异常，没有可用网络", Toast.LENGTH_SHORT).show();
				}

    	}
    };
	
	private EditText.OnEditorActionListener editorListener = new EditText.OnEditorActionListener() {
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if(actionId==EditorInfo.IME_ACTION_SEARCH){
				if(NetWorkStatus()) {
					String keyword = field_keyword.getText().toString();
					if(keyword!=null && !"".equals(keyword)) {
						Intent intent = new Intent();
						intent.setClass(MainActivity.this, ResultActivity.class);
						Bundle bundle = new Bundle();
			    		bundle.putString("city", city);
			    		bundle.putString("keyword", keyword);
			    		intent.putExtras(bundle);
			    		startActivity(intent);
					}
				} else {
					Toast.makeText(MainActivity.this, "网络异常，没有可用网络", Toast.LENGTH_SHORT).show();
				}
			}
			return false;
		}
	};
	
	private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
//			Intent intent = new Intent();
//			intent.setClass(MainActivity.this, CategoryActivity.class);
//			startActivity(intent);
//			overridePendingTransition(R.anim.main_enter, R.anim.main_exit);
			//ResultActivity.this.finish();
			Toast.makeText(MainActivity.this, "正在开发中，敬请期待...", Toast.LENGTH_SHORT).show();
		}
	};
	
	public class GridAdapter extends BaseAdapter 
	{
		private LayoutInflater inflater;
		
		public GridAdapter(Context context) 
		{
			inflater = LayoutInflater.from(context);
		}

		public final int getCount() 
		{
			return 6;
		}

		public final Object getItem(int paramInt) 
		{
			return null;
		}

		public final long getItemId(int paramInt) 
		{
			return paramInt;
		}

		public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) 
		{
			paramView = inflater.inflate(R.layout.activity_label_item, null);
			TextView text = (TextView)paramView.findViewById(R.id.activity_name);
			text.setTextSize(15);
			text.setTextColor(color.text_color_grey);
			
			switch(paramInt)
			{
				case 0:
				{
					text.setText("美食");
					Drawable draw = getResources().getDrawable(R.drawable.food);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 1:
				{
					text.setText("小吃快餐");	
					Drawable draw = getResources().getDrawable(R.drawable.snack);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 2:
				{
					text.setText("咖啡厅");	
					Drawable draw = getResources().getDrawable(R.drawable.coffee);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 3:
				{
					text.setText("电影院");	
					Drawable draw = getResources().getDrawable(R.drawable.film);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 4:
				{
					text.setText("KTV");	
					Drawable draw = getResources().getDrawable(R.drawable.ktv);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 5:
				{
					text.setText("更多分类");	
					Drawable draw = getResources().getDrawable(R.drawable.more);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
//				case 6:
//				{
//					text.setText("最近浏览");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_history);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
//				
//				case 7:
//				{
//					text.setText("个人中心");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
//				case 8:
//				{
//					text.setText("更多");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_more);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
			}

			paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density));
			paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3));
			
			return paramView;
		}
	}
    
	public void initPhoneInfo() {
		TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
//		String model = Build.MODEL; //手机型号
//		String phoneNo = tm.getLine1Number(); //手机号码
//		String imei = tm.getDeviceId(); //IMEI
//		String simSN = tm.getSimSerialNumber(); //sim卡序列号
//        String country = tm.getNetworkCountryIso(); //国家
//        String providerNo = tm.getNetworkOperator(); //运营商编号
		String provider = tm.getNetworkOperatorName(); //运营商
		String imsi = tm.getSubscriberId(); //IMSI
		PhoneUtil util = new PhoneUtil();
		PhoneInfo info = null;
		try {
			if(NetWorkStatus()) {
				info = util.getPhoneNoByIMSI(imsi);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        view_provider.setText(provider);
        if(info!=null && !"".equals(info.getPhoneNo())) {
        	view_phoneNo.setText(info.getPhoneNo());
        }
	}
	
	
    protected static final int MENU_ABOUT = Menu.FIRST;
    protected static final int MENU_Quit = Menu.FIRST+1;
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ABOUT, 0, " 关于 ...");
		menu.add(0, MENU_Quit, 0, " 结束 ");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case MENU_ABOUT:
			openOptionsDialog();
			break;
		case MENU_Quit:
			showExitAlert();
			break;
		}
		return true;
		}
	
	private void openOptionsDialog() { 
		new AlertDialog.Builder(MainActivity.this)
		.setTitle(R.string.about_title)
		.setMessage(R.string.about_msg)
		.setPositiveButton(R.string.confirm,
				new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {}
				})
		.setNegativeButton(R.string.homepage_label,
				new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialoginterface, int i){
							//go to url
							Uri uri = Uri.parse(getString(R.string.homepage_uri));
							Intent intent = new Intent(Intent.ACTION_VIEW, uri);
							startActivity(intent);
						}
				})
		   .show();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 按下键盘上返回按钮
		if(keyCode == KeyEvent.KEYCODE_BACK ){
			showExitAlert();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	private void showExitAlert() {
        new AlertDialog.Builder(this)
        .setTitle(R.string.prompt)
        .setMessage(R.string.quit_desc)
        .setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {}
                })
        .setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    	exitApp();
                    }
                }).show();
	}
	
	//彻底关闭程序
	protected void exitApp() {
	    super.onDestroy();
	    System.exit(0);
	    // 或者下面这种方式
	    // android.os.Process.killProcess(android.os.Process.myPid());
	}
	
    /**
     * 隐藏软键盘
     */
    private void hideInput(EditText editText){
    	InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
	
    private boolean NetWorkStatus() {
    	boolean netSataus = false;
    	ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	cwjManager.getActiveNetworkInfo();
    	if (cwjManager.getActiveNetworkInfo() != null) {
    		netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
    	}
//    	if (netSataus) {
//    		Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?");
//    		b.setPositiveButton("是", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				Intent mIntent = new Intent("/");
//    				ComponentName comp = new ComponentName("com.android.settings", 
//    						"com.android.settings.WirelessSettings");
//    				mIntent.setComponent(comp);
//    				mIntent.setAction("android.intent.action.VIEW");
//    				startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作，可以重写操作代码，在这里不再重写
//    			}
//    		}).setNeutralButton("否", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				dialog.cancel();
//    			}
//    		}).show();	
//    	}
    	return netSataus;
    }
    
}
